package com.zhongan.gateway.web.common;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import com.zhongan.gateway.common.exception.GatewayException;

public class BaseController {
    private static final Logger LOG                  = LoggerFactory.getLogger(BaseController.class);

    /** 默认分页起始点 */
    public static final int     DEFAULT_OFFSET       = 0;

    /** 默认分页大小 */
    public static final int     DEFAULT_PAGESIZE     = 12;

    /** 导出最大的条数 */
    public static final int     DEFAULT_MAX_PAGESIZE = 20000;

    @ExceptionHandler(GatewayException.class)
    public ResultBase<String> handleGatewayException(GatewayException ex, HttpServletRequest request) {
        LOG.warn(ex.getMessage(), ex);
        ResultBase<String> base = new ResultBase<String>();
        base.setErrorMsg(ex.getMessage());
        base.setSuccess(false);
        base.setErrorCode(ex.getErrorCode());
        return base;
    }

    @ExceptionHandler(Exception.class)
    public ResultBase<String> handleUnexpectedException(Exception ex, HttpServletRequest request) {
        LOG.warn(ex.getMessage(), ex);
        ResultBase<String> base = new ResultBase<String>();
        base.setErrorMsg(ex.getMessage());
        base.setSuccess(false);
        base.setErrorCode("500");
        return base;
    }

    //
    //    private String subMsg(String msg) {
    //        String s = msg;
    //        if (StringUtils.isNotEmpty(msg) && msg.length() > 300) {
    //            s = msg.substring(0, 300);
    //        }
    //        return s;
    //
    //    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        simpleDateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
    }

    protected ResultBase<Object> getSucResultBase(Object t) {
        ResultBase<Object> base = new ResultBase<Object>();
        base.setSuccess(true);
        base.setValue(t == null ? "" : t);
        return base;
    }
}
